package com.zlp.sentinel.exception;

import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.zlp.sentinel.common.R;
import com.zlp.sentinel.common.RespCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 自定义sentinel统一异常
 * @date: 2021/11/11 11:22
 */
@Component
@Slf4j(topic = "MyBlockExceptionHandler")
public class MyBlockExceptionHandler implements UrlBlockHandler {
    @Override
    public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse response, BlockException e) throws IOException {


        log.info("handle BlockException:{}",e.getRule());
        RespCode respCode = null;
        if (e instanceof FlowException){
            respCode = RespCode.FLOW_EXCEPTION;
        }else if (e instanceof DegradeException) {
            respCode = RespCode.DEGRADE_EXCEPTION;
        }else if (e instanceof ParamFlowException) {
            respCode = RespCode.PARAM_FLOW_EXCEPTION;
        }else if (e instanceof SystemBlockException) {
            respCode = RespCode.SYSTEM_BLOCK_EXCEPTION;
        }else if (e instanceof AuthorityException) {
            respCode = RespCode.AUTHORITY_EXCEPTION;
        }

        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().println(JSONUtil.parse(R.failed(respCode)));
        response.getWriter().flush();
    }
}
